const express = require('express')
const { queryDBPromise } = require('../db/utildb')

const goodsRouter = express.Router()

/**
 * 修改商品
 *   method:put
 *   url:/goods/1
 *   参数:id :number
 *   描述: 根据id修改商品名称
 */
goodsRouter.put('/goods/:id', (req, res) => {
	const id = req.params.id
	const name = req.body.name

	// 根据id修改数据库中商品名称
	// 字符串变量，需要引号，
	const sql = `UPDATE goods SET name = "${name}" WHERE id = ${id}`
	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			message: '修改商品成功！',
		})
	})
})

/**
 * 商品列表
 * Method: Get
 * url: /goods
 *
 */
goodsRouter.get('/goods', (req, res) => {
	const sql = `SELECT id,name,price,num FROM goods`
	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			list: data,
		})
	})
})

/**
 * 获取ID为1的商品
 *   method: GET
 *   url: /goods/1
 */
goodsRouter.get('/goods/:id', (req, res) => {
	const id = req.params.id // 商品id

	const sql = `SELECT id,name,price,num FROM goods WHERE id=${id}`

	queryDBPromise(sql).then(data => {
		console.log('data : ', data) // 数组

		if (data.length > 0) {
			res.send({
				code: 1,
				good: data[0],
			})
		} else {
			res.send({
				code: -1,
				message: '商品不存在!',
			})
		}
	})
})

/**
 * 商品添加
 *  method:post
 *  url: /goods
 *  参数: id: number   //商品id
 *        name: string 名称
 *        price:number  价格
 *        num: num  数量
 */
goodsRouter.post('/goods', (req, res) => {
	//1. 接收商品数据
	//2. 添加商品到数组
	//3. 响应添加成功
	const name = req.body.name // 商品名称
	const price = req.body.price // 商品价格
	const num = req.body.num // 商品数量

	// 保存数据库goods
	const sql = `INSERT INTO goods (name,price,num)VALUES('${name}',${price},${num})`

	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			message: '添加商品成功',
		})
	})
})

/**
 * 商品删除
 *    method: delete
 *    url:  /goods/1001
 *
 */
goodsRouter.delete('/goods/:id', (req, res) => {
	//1.接收删除商品id
	//2.删除数组中商品
	//3.响应删除成功
	// const id = req.query.id // id=1001
	const id = req.params.id // id=1001

	const sql = `DELETE FROM goods WHERE id = ${id}`
	queryDBPromise(sql).then(data => {
		console.log('data ', data)

		res.send({
			code: 1,
			message: '删除商品成功',
		})
	})
})

module.exports = {
	goodsRouter,
}
